iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
Vue.js

Vue.js 新手入門之路系列 第 6

Vue.js 新手入門之路 - 條件渲染

  • 分享至 

  • xImage
  •  

條件判斷

今天要學習 v-if 的用法,它依照表達式的真假值來決定是否渲染該元素

  • True --> 渲染
  • False --> 不渲染

eg.

<template>
    <div class="box">
        <p v-if="seen"> now U C me</p>
    </div>
</template>

<script>
export default {
  data() {
    return {
        seen:true
        // seen:false
    }
  }
}
</script>

<style scoped>
    .box{
        text-align: center;
        border: solid;
        margin-left: 850px;
        height: 60px;
        width:250px;
    }
</style>

p 標籤會由 seen 決定是否渲染
https://ithelp.ithome.com.tw/upload/images/20250826/20178296oq9EHNfRQK.png https://ithelp.ithome.com.tw/upload/images/20250826/20178296mRX6bR3GQM.png
這邊可以看到如果帶值是 False 元素會呈現註解的狀態
https://ithelp.ithome.com.tw/upload/images/20250826/20178296TOqGGE0fpS.png

v-if 也可以搭判配 v-else-if 或是 v-else,而一個 v-else 元素必須跟在一個 v-ifv-else-if 元素後面,否則 Vue 無法識別
這邊延伸範例,用亂數讓 message 可以變動

<template>
    <div class="box">
        <p v-if="message === 'A'">Case A</p>
        <p v-else-if="message === 'B'">Case B</p>
        <p v-else-if="message === 'C'">Case C</p>
        <p v-else>Case D</p>
        <button @click="change">Press Me</button>
    </div>
</template>

<script>
export default {
  data() {
    return {
        message:'A'
    }
  },
  methods:{
    change(){
        let options = ['A', 'B', 'C', 'D']
        let randomIndex = Math.floor(Math.random() * options.length)
        this.message = options[randomIndex]
    }
  }
}
</script>

<style scoped>
    .box{
        text-align: center;
        border: solid;
        margin-left: 850px;
        height: 120px;
        width:250px;
    }
    button{
        border: solid;
        border-color: orange;
    }
</style>

今天順便多學了綁定事件的方式 v-on ,之後會再更深入了解

ref:
https://cn.vuejs.org/guide/essentials/event-handling.html
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/random
https://book.vue.tw/CH1/1-4-directive.html


上一篇
Vue.js 新手入門之路 - 模板語法 (二)
下一篇
Vue.js 新手入門之路 - 響應式基礎
系列文
Vue.js 新手入門之路18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言